import React, { useEffect } from "react";
import { useAppDispatch, useAppSelector } from "../../hooks";
import { fetchCategories, selectCategories } from "../../../features/categories/categoriesSlice";
import { Link } from "react-router-dom";
import { Category } from "../../../types/category";
import styles  from  "./Home.module.css";

const Home = () => {
    const categories  = useAppSelector(selectCategories);
    const dispatch = useAppDispatch();

    useEffect(() => {
        dispatch(fetchCategories());
    }, [dispatch]);

    const renderCategories = () => {
        return categories.map((category: Category) => {
            return (
                <Link to={`categories/${category.key}`} key={category.key}>
                    <div className={styles["categories__item"]} >
                        <span className={styles["categories__item-name"]}>{ category.title }</span>
                    </div>
                </Link>
            );
        });
    };

    return (
        <div>
            <div className={styles.categories}>
            <div className={styles["categories__list"]}>
                {categories?.length ? renderCategories() : <span>No categories</span>}
            </div>
          </div>
        </div>
    );
}

export default Home;
